import styles from "./dialog-list.module.scss";
import {DialogResizableSidebar} from "@/app/components/dialog/dialog-resizable-sidebar";
import {DialogItem} from "@/app/components/dialog/dialog-item";
import {useNavigate} from "react-router-dom";
import {userChatStore} from "@/app/store/chat-store";
import DialogHead from "@/app/components/dialog/dialog-head";

/**
 * 对话框列表
 */
export function DialogList() {
    const navigate = useNavigate();
    const chatStore = userChatStore();
    const [sessions, currentSessionIndex, selectSession, deleteSession] = userChatStore((state) => [
        state.sessions,
        state.currentSessionIndex,
        state.selectSession,
        state.deleteSession
    ])

    return (
        // DialogResizeableSidebar 用于调整对话栏的大小
        <DialogResizableSidebar>
            {/*头部操作*/}
            <DialogHead/>
            {/*对话列表*/}
            <div className={styles["dialog-list"]}>
                {/*循环遍历数据，当有数据变更时会自动刷新到页面*/}
                {sessions.map((session, index) => (
                    <DialogItem
                        key={session.id}
                        session={session}
                        selected={currentSessionIndex === index}
                        onClick={() => {
                            selectSession(index);
                            navigate(`/chat/${session.id}`, {state: {title: session.dialog.title}});
                        }}
                        onClickDelete={() => {
                            deleteSession(index);
                            navigate(`/chat/${currentSessionIndex}`, {state: {title: sessions[currentSessionIndex].dialog.title}});
                        }}
                    />
                ))}
            </div>
        </DialogResizableSidebar>
    )
}
